package jjn.round1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2022-09-28 14:24
 */
public class LeetCode22_GenerateParentheses {
    
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        backtrack(result, 0, 0, n, new StringBuilder());
        return result;
    }
    
    private void backtrack(List<String> result, int open, int close, int max, StringBuilder cur) {
        if (cur.length() == 2 * max) {
            result.add(cur.toString());
            return;
        }
        if (open < max) {
            cur.append('(');
            backtrack(result, open + 1, close, max, cur);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (close < open) {
            cur.append(')');
            backtrack(result, open, close + 1, max, cur);
            cur.deleteCharAt(cur.length() - 1);
        }
    }
}
